package com.zzuli.practice.controller;

import com.zzuli.practice.entity.Comment;
import com.zzuli.practice.entity.Result;
import com.zzuli.practice.entity.User;
import com.zzuli.practice.service.impl.CommentService;
import com.zzuli.practice.service.impl.LoginService;
import com.zzuli.practice.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
public class CommentController implements Constant {

    @Autowired
    private CommentService commentService;

    @Autowired
    private LoginService loginService;

    @RequestMapping("getcomment/{postid}")
    public Result getComment(@PathVariable("postid") Integer postid){
        Result result = new Result();
        try{
            List<Comment> commentList = commentService.selectCommentByPostId(postid);
            result.setStatusCode(SUCCESS);
            result.setMessage("查询成功");
            result.setData(commentList);
        } catch (Exception e){
            e.printStackTrace();
            result.setStatusCode(FAILURE);
            result.setMessage("查询失败");
        }
        return result;
    }

    @RequestMapping(value = "/insertcomment", method = RequestMethod.POST)
    public Result addComment(Integer postid, String username, String content){
        Result result = new Result();

        if (username == null){
            result.setStatusCode(FAILURE);
            result.setMessage("未登录");
            return result;
        }

        User user = loginService.selectByUserName(username);
        Comment comment = new Comment();
        comment.setPostid(postid);
        comment.setUsername(username);
        comment.setContent(content);
        comment.setCreatetime(new Date());
        comment.setHeaderimg(user.getHeaderimg());

        try {
            int i = commentService.insertComment(comment);
            if (i == 1){
                result.setStatusCode(SUCCESS);
                result.setMessage("添加成功");
            } else {
                result.setStatusCode(FAILURE);
                result.setMessage("添加失败");
            }
        } catch (Exception e){
            e.printStackTrace();
            result.setStatusCode(FAILURE);
            result.setMessage("添加失败");
        }

        return result;

    }

}
